package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.AutoFill;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.BusinessException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {


    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private  SetmealMapper setmealMapper;


    // 菜品新增
    @Transactional
    @Override
    public void saveDishWithFlavor(DishDTO dishDTO) {
        // 1.参数校验
        // 2.业务校验
        Dish oldDish = dishMapper.getByName(dishDTO.getName());
        if (oldDish != null) {
            throw new BusinessException("菜品已存在");
        }
        // 3.菜品dto->菜品entity
        Dish dish = BeanUtil.copyProperties(dishDTO, Dish.class);
        // 4.补充状态
        dish.setStatus(StatusConstant.DISABLE); // 禁用
        // 5.调用dishMapper新增 （主键返回）
        log.info("菜品新增前id：{}", dish.getId());
        dishMapper.insert(dish);
        log.info("菜品新增后id：{}", dish.getId());

        // 6. 取出口味列表
        List<DishFlavor> flavorList = dishDTO.getFlavors();
        // 7.遍历（非空判断）
        /*if (flavorList!=null && flavorList.size()>0) {}*/
        if (ArrayUtil.isNotEmpty(flavorList)) {
            for (DishFlavor dishFlavor : flavorList) {
                // 关联菜品id
                dishFlavor.setDishId(dish.getId());
                // 保存口味
                dishFlavorMapper.insert(dishFlavor);
            }
        }
    }

    // 分页
    @Override
    public PageResult getPage(DishPageDTO dishPageDTO) {
        // 1.开启分页
        PageHelper.startPage(dishPageDTO.getPage(), dishPageDTO.getPageSize());
        // 2.查询list
        List<DishVO> voList = dishMapper.getList(dishPageDTO);
        Page<DishVO> page = (Page<DishVO>) voList;
        // 3.返回分页
        return new PageResult(page.getTotal(), page.getResult());

    }

    // 回显菜品
    @Override
    public DishVO getById(Long id) {
        // 1.先查菜品
        Dish dish = dishMapper.getById(id);
        // 2.再根据菜品id查询口味列表
        List<DishFlavor> flavorList = dishFlavorMapper.getListByDishId(id);
        // 3.封装vo
        DishVO dishVO = BeanUtil.copyProperties(dish, DishVO.class);
        dishVO.setFlavors(flavorList);
        // 4.返回vo
        return dishVO;
    }

    //修改菜品
    @Transactional
    @Override
    public void updateById(DishDTO dishDTO) {
        //dto转实体
        Dish dish = BeanUtil.copyProperties(dishDTO, Dish.class);
        //修改
        dishMapper.updateById(dish);
        //删除旧口味
        dishFlavorMapper.deleteByDishId(dish.getId());
        //新增新口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //非空判断
        if (ArrayUtil.isNotEmpty(flavors)) {
            //遍历
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
                //添加
                dishFlavorMapper.insert(flavor);
            }
        }
    }

    //删除菜品
    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {
        //查询菜品的售卖状态
        for (Long id : ids) {
            if (dishMapper.getById(id).getStatus().equals(StatusConstant.ENABLE)) {
                throw new BusinessException("菜品处于启售状态,无法删除");
            }
        }
        //查询菜品是否与套餐绑定
        if (setmealDishMapper.countByDishIds(ids)>0) {
            throw new BusinessException("菜品与套餐绑定,无法删除");
        }
        //删除菜品及对应口味
        for (Long id : ids) {
            dishMapper.deleteById(id);
            dishFlavorMapper.deleteByDishId(id);
        }

    }

    //启用/禁用
    @Transactional
    @Override
    public void StartOrStop(Integer status, Long id) {
        //封装
        Dish dish=Dish.builder()
                .status(status)
                .id(id)
                .build();
        //复用修改代码
        dishMapper.updateById(dish);
        //判断状态
        if (status.equals(StatusConstant.DISABLE)){
            setmealMapper.updateStatusByDishId(id);
        }
    }

    // 查询菜品列表
    @Override
    public List<DishVO> getList(DishPageDTO dishPageDTO) {
        return dishMapper.getList(dishPageDTO);
    }
    // 条件查询
    @Override
    public List<DishVO> getParamList(DishPageDTO dishPageDTO) {
        // 1.先查询菜品列表
        List<DishVO> voList = dishMapper.getList(dishPageDTO);

        // 2.遍历菜品
        voList.forEach(dishVO -> {
            // 根据菜品id查询口味
            List<DishFlavor> flavorList = dishFlavorMapper.getListByDishId(dishVO.getId());
            // 将口味封装到vo
            dishVO.setFlavors(flavorList);
        });

        // 3.返回
        return voList;
    }

}
